package logic

import (
	"context"
	"fmt"
	"mall/model/mysql"
	"mall/model/redis"
	"mall/pkg"

	"mall/mallrpc/internal/svc"
	"mall/mallrpc/mallrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type UserLoginLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewUserLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UserLoginLogic {
	return &UserLoginLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *UserLoginLogic) UserLogin(in *mallrpc.UserLoginRequest) (*mallrpc.UserLoginResponse, error) {
	// todo: add your logic here and delete this line

	get := redis.Client.Get("sendSmslogin" + in.Tel)
	if get.Val() != in.Code {
		return nil, fmt.Errorf("短信验证码错误，请重新输入")
	}
	var finduser mysql.User
	mysql.DB.Debug().Model(&mysql.User{}).Find(&finduser)
	if finduser.ID == 0 {
		return nil, fmt.Errorf("用户未注册，请前往注册")
	}
	if finduser.Password != pkg.Pwdmd5(in.Password) {
		return nil, fmt.Errorf("密码错误，请重新输入")
	}
	redis.Client.Del("sendSmslogin" + in.Tel)

	return &mallrpc.UserLoginResponse{Id: int64(finduser.ID)}, nil
}
